package cn.jdy.plugins.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.SpringUploadFile;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.Doc;
import cn.jdy.plugins.entity.Download;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.DocService;
import cn.jdy.plugins.service.DownloadService;

/**
 * 营销智库控制类
 * Created by Tianyi on 2014/7/10.
 */
@Controller
@RequestMapping("/doc")
public class DocCtrl extends BaseCtrl {
	@Autowired
	private DocService docService;
	@Autowired
	private DownloadService downloadService;
	/**
	 * 营销智库列表
	 * @param entity
	 * @param s
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(Doc entity, String s, boolean m) {
		ModelAndView mv = new ModelAndView(m?"/my/myDoc.jsp":"/doc/docList.jsp");
		try {
			//设置分页信息
			if(entity.getiDisplayLength() == 0) entity.setiDisplayLength(10);
			if(entity.getPageNo() <= 0) entity.setPageNo(1);
			entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength());

			if(m) {
				String date = DateUtil.getCurrentDate2();
				int month = DateUtil.getMonth() - 1;
				if(month > 0) {
					date = date.replaceFirst("-\\d{2}", (month<10?"-0":"-") + month);
				}else {
					date = date.replaceFirst("\\d{4}-\\d{2}", (DateUtil.getYear() - 1) + "-12");
				}
				entity.setUserId(getMember(false).getId());
				entity.setCreateTime(date);
			}else {
				if(s!=null && s.length()>0) entity.setKeyword(s);
				entity.setStatus("1");
			}

			mv.addObject("dataList", docService.query(entity));
			mv.addObject("total", docService.count(entity));
			mv.addObject("pageNo", entity.getPageNo());
			mv.addObject("size", entity.getiDisplayLength());
			mv.addObject("hotData", docService.queryTops("readTimes", false));
			mv.addObject("newData", docService.queryTops("createTime", false));
			mv.addObject("bizClass", super.bizClass(GlobalConstant.TYPE_DOC));
			mv.addObject("entity", entity);
			mv.addObject("keywords", s);

		} catch(Exception e) {
			BaseLog.e(this.getClass(), "list", e);
		}
		return mv;
	}

	/**
	 * 查看智库详情
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail/{id}")
	public ModelAndView detail(@PathVariable long id) {
		ModelAndView mv = new ModelAndView("/doc/docDetail.jsp");
		try {
			mv.addObject("entity", docService.find(id));
			mv.addObject("bizClass", super.bizClass(GlobalConstant.TYPE_DOC));
			//增加一次访问量
			docService.addOneTime(id, 'r');
			mv.addObject("doctotal", docService.count("status", "1"));

			Member member = super.getMember(false);
			if(member!=null && downloadService.isDownload(member.getId(), id)) {
				mv.addObject("has", "yes");
			}

			mv.addObject("hotData", docService.queryTops("readTimes", false));
      mv.addObject("newData", docService.queryTops("createTime", false));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "detail", e);
		}
		return mv;
	}

	/**
	 * 点赞
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/goodTimes/{id}")
	public void addGoodTimes(@PathVariable long id) {
		docService.addOneTime(id, 'g');
	}

	/**
	 * 初始化添加页面
	 *
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 初始化添加页面
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/doc/docEdit.jsp");
		if(id!=null) mv.addObject("entity", docService.find(id));
		//mv.addObject("bizClass", this.confService.queryByType(GlobalConstant.TYPE_DOC, null));
		mv.addObject("bizClass", super.bizClass(GlobalConstant.TYPE_DOC));
		return mv;
	}

	
	@RequestMapping(value = "/forUpload")
	@ResponseBody
	public Map<String, Object> forUpload(DefaultMultipartHttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String savePath = "userDoc";
		try {
			
			//附件是否为空
			if(!request.getFile("file").isEmpty()) {
				int MAX_SIZE = 200000 * 1024;
				String[] allowFiles = {".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".vsd", ".pot", ".pps", ".rtf", 
						".wps", ".et", ".dps", ".pdf", ".txt", ".epub"};
				Map<String, String> reMap = SpringUploadFile.uploadFile(request, savePath, MAX_SIZE, allowFiles);
				if(StringUtil.isNullOrEmpty(reMap.get("errorInfo"))) {
					jsonMap.put("newUrl", reMap.get("newUrl"));
				} else {
					jsonMap.put("errorInfo", reMap.get("errorInfo"));
				}
			}
		}catch(BaseException e) {
			BaseLog.e(this.getClass(), "会员 头像预览失败", e);
		}
		return jsonMap;
	}



		/**
	 * 保存智库
	 * 成功返回个人中心 我的文章列表页面 失败返回编辑页面
	 *
	 * @param entity
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(Doc entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			//会员信息
			Member member = getMember(true);

			if("0".equals(entity.getPaymentType())){
				entity.setScore(0);
			}
			//是否新增
			if(entity.getId() == null) {
				entity.setUserType("F");
				entity.setStatus("0");
				entity.setUserId(member.getId());
				entity.setUserName(member.getUserName());
				entity.setCreateTime(DateUtil.getCurrentTime());
				this.docService.save(entity);
			} else {
				this.docService.update(entity);
			}
			//赠送积分
			memberService.updateMoney(member.getId(), GlobalConstant.SCORE_DOC_ADD);
			
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "文章保存异常！", e);
		}
		return jsonMap;
	}
	

	/**
	 * 判断是否符合下载条件
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/check/{id}")
	@ResponseBody
	public Map<String, Object> check(@PathVariable long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			Member member = getMember(true);
			if(member != null) {
				Doc doc = docService.find(id);
				if(doc != null) {
					//判断此智库是否是当前用户提供的，如果是当前用户提供
					if(doc.getScore() == 0 || String.valueOf(member.getId()).equals(doc.getUserId())) {
						jsonMap.put("statusCode", 200);
					} else {
						//判断用户是否下载过此文件
						if(downloadService.isDownload(member.getId(), id)) {
							jsonMap.put("statusCode", 200);
						} else {
							if(member.getScore() != null && member.getScore() >= doc.getScore()) {
								jsonMap.put("statusCode", 201);
								jsonMap.put("msg", "本地下载将会扣除您" + doc.getScore() + "积分，是否下载？");
							} else {
								jsonMap.put("statusCode", 501);
								jsonMap.put("msg", "您的积分不够！");
							}
						}
					}
				} else {
					throw new RuntimeException("查询智库异常：" + member.getId());
				}
			} else {
				jsonMap.put("statusCode", 502);
				jsonMap.put("msg", "请登录后下载！");
			}
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			jsonMap.put("msg", "对不起，不支持下载！");
			BaseLog.e(this.getClass(), "查询错误", e);
		}
		return jsonMap;
	}

	/**
	 * 智库下载
	 *
	 * @param id
	 * @param response
	 */
	@RequestMapping("/down/{id}")
	@ResponseBody
	public void down(@PathVariable long id, HttpServletResponse response) {
		Doc doc = docService.find(id);
		if(doc == null) return;
		String fileUrl = doc.getFileUrl();
		if(fileUrl == null || fileUrl.isEmpty()) return;
		File file = new File(GlobalConstant.PROJECT_UPLOAD_PATH + fileUrl);
		if(!file.exists()) {
			BaseLog.e(this.getClass(), "找不到文件:" + file);
			return;
		}

		Member member = getMember(true);
		//判断用户是否下载过此文件
		if(downloadService.isDownload(member.getId(), id)) {
			downloadService.addOneTime(member.getId(), id);
		} else {
			Download download = new Download();
			download.setDocId(doc.getId());
			download.setUserId(member.getId());
			download.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			download.setCount(1);
			if(!member.getId().equals(doc.getUserId())) {
				download.setScore(doc.getScore());
				member.setScore(member.getScore() - doc.getScore());
				try {
					memberService.update(member);
				} catch(Exception e) {
					BaseLog.e(this.getClass(), "扣除会员积分异常：" + member.getId(), e);
				}
				try {
					member = memberService.find(doc.getUserId());
					if(member != null) {
						member.setScore(member.getScore() + doc.getScore());
						memberService.update(member);
					}
				} catch(Exception e) {
					BaseLog.e(this.getClass(), "赠送会员积分异常：" + doc.getUserId(), e);
				}
			}
			downloadService.save(download);
		}

		// 增加一次下载次数
		docService.addOneTime(id, 'd');

		OutputStream out = null;
		InputStream inStream = null;
		try {
			//准备下载文件
			response.reset();
			request.setCharacterEncoding("UTF-8");
			int extension = fileUrl.lastIndexOf(".");
			String name = doc.getTitle() + (extension > -1 ? fileUrl.substring(extension) : "");
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
			int i = -1;
			inStream = new FileInputStream(file);
			out = response.getOutputStream();
			while((i = inStream.read()) != -1) {
				out.write(i);
			}
			out.flush();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "down:输出流输出时错误!", e);
		} finally {
			try {
				inStream.close();
				out.close();
			} catch(IOException e) {
				BaseLog.e(this.getClass(), "关闭流时出错", e);
			}
		}
	}

	/*******************************个人中心业务******************************/
	/**
	 * 查询我的下载
	 * @param download
	 * @return
	 */
	@RequestMapping("/listDown")
	public ModelAndView listDown(Download download, String fromDate, String toDate) {
		ModelAndView mv = new ModelAndView("/my/myDown.jsp");

		try {
			if(download.getPageNo()==0) download.setPageNo(1);
			if(download.getiDisplayLength()==0) download.setiDisplayLength(5);
			download.setiDisplayStart((download.getPageNo()-1)*download.getiDisplayLength());
			
		    download.setUserId(getMember(false).getId());
		    
			mv.addObject("dataList", downloadService.query(download));
			mv.addObject("total", downloadService.count(download));
			mv.addObject("pageNo", download.getPageNo());
			mv.addObject("size", download.getiDisplayLength());
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询我的下载", e);
		}
		
		return mv;
	}
}
